<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <table border="1" cellspacing="0">
        <thead>
            <tr>
                <th>序号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>操作</th>
            </tr>
        <tbody>

        </tbody>
        </thead>
    </table>
    <script src="./lib/jquery/jquery-3.3.1.js"></script>
    <script src="./lib/art-template/art-template.js"></script>
    <script type="text/template" id="temp">
        <% for (var i = 0; i < list.length; i++) { %> 
            <tr>
                <td><%= i %></td>
                <td><%= list[i].username %></td>
                <td><%= list[i].password %></td>
                <td><a href="javascript:;" data-id="<%= list[i].id %>">删除</a></td>
            </tr>
        <% } %>
    </script>
    <script>
        //显示： 每次页面刷新或打开时就重新发送请求到服务器查询数据，重新渲染模板
        let show = function () {
            $.ajax({
                type: 'get',
                url: '/show',
                data: '',
                success: function (result) {
                    // template(模板id, 数据对象);
                    let str = template('temp', { list: result });
                    // 将渲染好的模板，加入元素中,html方法会覆盖原先的
                    $('tbody').html(str);
                }
            })
        }
        show();
        //删除：每次点击删除按钮，删除掉一行都调用show方法刷新页面
        // 事件委托给tbody
        $('tbody').on('click', 'a', function () {
            let id = $(this).attr('data-id');
            $.ajax({
                type: 'get',
                url: '/deluser',
                data: 'id=' + id,
                success: function (result) {
                    if(result.code == '10001') {
                        // 删除成功就刷新页面
                        show();
                    }
                }
            })
        });
    </script>
</body>

</html>